import React, { useImperativeHandle, useState } from 'react';
import { Form, Input, message, Modal } from 'antd';
import { SmsTempInfo } from 'admin/schema/SmsTemplate';
import { createSmsTemp, editSmsTemp } from 'admin/servers/servers';
import TextArea from 'antd/lib/input/TextArea';
import { verifyNull } from 'utils/tools';

type IProps = {
  cRef: any;
};
// 存储回调函数
let ok = () => {};
const SmsPop: React.FC<IProps> = ({ cRef }) => {
  const [form] = Form.useForm();
  const [formData, setFormData] = useState<any>({});
  const [isEdit, setIsEdit] = useState<boolean>(false);
  const [visible, setVisible] = useState<boolean>(false);

  const open = (obj: SmsTempInfo, cb: any) => {
    setVisible(true);
    ok = cb;
    if (obj.templateId) {
      // 编辑弹窗，需要初始化表单数据，赋值
      setFormData(obj);
      form.setFieldsValue(obj);
      setIsEdit(true);
    } else {
      // 新增弹窗
      setFormData(obj);
    }
  };
  useImperativeHandle(cRef, () => ({
    open: (obj: any, cb: any) => open(obj, cb),
  }));
  const handleOK = () => {
    form.validateFields().then(() => {
      // 表单验证通过
      const val = form.getFieldsValue() as SmsTempInfo;
      // 请求接口
      if (!isEdit) {
        // 创建
        createSmsTemp({ ...val })
          .then(res => {
            message.success('创建成功');
            // 关闭弹窗
            handleClose();
            // 执行回调刷新
            ok();
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      } else {
        // 修改
        editSmsTemp(formData.templateId, { ...val })
          .then(res => {
            message.success('编辑成功');
            // 关闭弹窗
            handleClose();
            // 执行回调刷新
            ok();
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      }
    });
  };
  const handleClose = () => {
    // 恢复默认
    setFormData({});
    form.resetFields();
    setVisible(false);
    setIsEdit(false);
  };

  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 18 },
  };

  return (
    <Modal
      width={600}
      title={isEdit ? '编辑短信模板' : '新建短信模板'}
      visible={visible}
      onOk={handleOK}
      onCancel={handleClose}
    >
      <Form {...layout} form={form} layout="horizontal">
        <Form.Item
          label="模板名称"
          name="templateName"
          rules={verifyNull('请输入模板名称')}
          getValueFromEvent={event => {
            return event.target.value.replace(/\s+/g, '');
          }}
        >
          <Input placeholder="请输入0-20位以内字符" maxLength={20} allowClear />
        </Form.Item>
        <Form.Item label="短信内容" name="content" rules={verifyNull('请输入短信内容')}>
          <TextArea
            rows={10}
            // eslint-disable-next-line no-template-curly-in-string
            placeholder="请输入0-500位以内字符，变量以${}标识，例如${用户姓名}"
            maxLength={500}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default SmsPop;
